package com.example.pdfandword.util;


import com.example.pdfandword.controller.DisUser;
import com.example.pdfandword.controller.TableEntity;
import com.example.pdfandword.word.WordTemplateUtilities;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WordUtil {
    /*
     * 生成word文档工具类
     */
    /**
     * 导出word
     * <p>第一步生成替换后的word文件，只支持docx</p>
     * <p>第二步下载生成的文件</p>
     * <p>第三步删除生成的临时文件</p>
     * 模版变量中变量格式：{{foo}}
//     * @param templatePath word模板地址
//     * @param temDir 生成临时文件存放地址
//     * @param fileName 文件名
//     * @param params 替换的参数
//     * @param request HttpServletRequest
//     * @param response HttpServletResponse
     */
   /* public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        Assert.notNull(templatePath,"模板路径不能为空");
        Assert.notNull(temDir,"临时文件路径不能为空");
        Assert.notNull(fileName,"导出文件名不能为空");
`-        Assert.isTrue(fileName.endsWith(".docx"),"word导出请使用docx格式");
        if (!temDir.endsWith("/")){
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            String userAgent = request.getHeader("user-agent").toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            }
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            String tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream out = response.getOutputStream();
            doc.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //delAllFile(temDir);//这一步看具体需求，要不要删
        }

    }*/
    public static String build(File tmpFile, Map<String, String> contentMap,String[] strs, List<TableEntity> list,String savaPath, String orderNo, String hetongcode, String contractType,String uploadType,Map<String, InputStream> inpustreammap) throws Exception {
        String fileurl = "";
        String filedoutpath =  savaPath  + orderNo  + "/out/";
        File fileout = new File(filedoutpath);
        if (!fileout.exists()) {
            fileout.mkdirs();// 创建文件根目录
        }
        String fileurlpdf = filedoutpath +hetongcode+".PDF";
        String fileurlword= filedoutpath +hetongcode+".docx";
        String fileurlwordtmp= filedoutpath +hetongcode+"12.docx";
        Map<String, Object> resultsLabel = new HashMap<String, Object>();
        resultsLabel.put("String", contentMap);
        Map<String, Object> resultsTable = new HashMap<String, Object>();
        resultsLabel.put("Table", resultsTable);

        resultsLabel.put("pic", inpustreammap);

        try{
            if(list != null){
                WordTemplateUtilities.GetInstance().toWord(tmpFile, fileurlwordtmp, resultsLabel);
                WordTemplateUtilities.GetInstance().downloadWord(list,strs,fileurlwordtmp,fileurlword);
            }else {
                WordTemplateUtilities.GetInstance().toWord(tmpFile, fileurlword, resultsLabel);
            }
        }catch (Exception e){
        }

        if("pdf".equals(contractType)){
            PdfConvertUtil.word2PDF(fileurlword,fileurlpdf);
            File file = new File(fileurlpdf);
            fileurl = OssBootUtil.uploadlocalfile(file,"hetong","");

        }else{
            File file = new File(fileurlword);

            fileurl = OssBootUtil.uploadlocalfile(file,"hetong","");

        }
        return  fileurl;
    }
    public static String buildandprint(File tmpFile, Map<String, String> contentMap,String[] strs, List<TableEntity> list,String savaPath, String orderNo, String hetongcode, String contractType,String uploadType,Map<String, InputStream> inpustreammap) throws Exception {
        String fileurl = "";
            String filedoutpath = savaPath + orderNo + "/out/";
            File fileout = new File(filedoutpath);
            if (!fileout.exists()) {
                fileout.mkdirs();// 创建文件根目录
            }
            String fileurlpdf = filedoutpath + hetongcode + ".PDF";
            String fileurlword = filedoutpath + hetongcode + ".docx";
            String fileurlwordtmp = filedoutpath + hetongcode + "12.docx";
            ConcurrentHashMap<String, Object> resultsLabel = new ConcurrentHashMap<String, Object>();
            resultsLabel.put("String", contentMap);
            ConcurrentHashMap<String, Object> resultsTable = new ConcurrentHashMap<String, Object>();
            resultsLabel.put("Table", resultsTable);
            resultsLabel.put("pic", inpustreammap);

            try {
                if (list != null) {
                    WordTemplateUtilities.GetInstance().toWord(tmpFile, fileurlwordtmp, resultsLabel);
                    WordTemplateUtilities.GetInstance().downloadWord(list, strs, fileurlwordtmp, fileurlword);
                } else {
                    System.out.println("======:" + tmpFile.getName() + "  fileurlword:" + fileurlword + "   resultsLabel:" + resultsLabel.get("pic"));
                    WordTemplateUtilities.GetInstance().toWord(tmpFile, fileurlword, resultsLabel);
                }
            } catch (Exception e) {
            }
            new PdfConvertUtil().printword(fileurlword);
        return  fileurl;
    }
    public static String buildpdf(File tmpFile, Map<String, String> contentMap, String savaPath,String orderNo,String hetongcode) throws Exception {
        String fileurl = "";
        String filedoutpath =  savaPath  + orderNo  + "/out/";
        File fileout = new File(filedoutpath);
        if (!fileout.exists()) {
            fileout.mkdirs();// 创建文件根目录
        }
        String fileurlpdf = filedoutpath +hetongcode+".PDF";
        String fileurlword= filedoutpath +hetongcode+".docx";
        Map<String, Object> resultsLabel = new HashMap<String, Object>();
        resultsLabel.put("String", contentMap);
        Map<String, Object> resultsTable = new HashMap<String, Object>();
        resultsLabel.put("Table", resultsTable);
        try{
            WordTemplateUtilities.GetInstance().toWord(tmpFile, fileurlword, resultsLabel);

        }catch (Exception e){

        }
//        try{
////            WordTemplateUtilities.convertWordToPdf(fileurlword, fileurlpdf);
////
////        }catch (Exception e){
////
////        }
//        WordTemplateUtilities.GetInstance().toWord(tmpFile, fileurlword, resultsLabel);
//        try{
//            WordTemplateUtilities.convertWordToPdf(fileurlword, fileurlpdf);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        File file = new File(fileurlword);
        fileurl = OssBootUtil.uploadlocalfile(file,"hetong","");
        return  fileurl;
    }
    public static void download(String urlString, String filename) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        OutputStream os = new FileOutputStream(filename);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }



    /**
     * 动态替换docx 表格内容 并下载
     */
    public static void downloadWord(List<DisUser> list, String inFilePath, String outFilePath){
        XWPFDocument document;

        //添加表格
        try {
            document = new XWPFDocument(POIXMLDocument.openPackage(inFilePath));// 生成word文档并读取模板
            //附表格
            XWPFTable ComTable = document.createTable();

            //列宽自动分割
            /*CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
            comTableWidth.setType(STTblWidth.DXA);
            comTableWidth.setW(BigInteger.valueOf(9072));*/

            //表格第一行
            XWPFTableRow comTableRowOne = ComTable.getRow(0);
            // 表格标题内容的填充
            // 因为document.createTable() 创建表格后默认是一行一列，所以第一行第一列是直接comTableRowOne.getCell(0).setText("序号"); 赋值的。
            // 第一行的其他列需要创建后才能赋值 comTableRowOne.addNewTableCell().setText("作品类型");
            comTableRowOne.getCell(0).setText("序号");
            comTableRowOne.addNewTableCell().setText("名称");
            comTableRowOne.addNewTableCell().setText("审批人");
            comTableRowOne.addNewTableCell().setText("审批时间");
            comTableRowOne.addNewTableCell().setText("审批意见");

            // 表格标题剧中+单元格大小设置
            setCellWitchAndAlign(comTableRowOne.getCell(0),"700",STVerticalJc.CENTER,STJc.CENTER);
            setCellWitchAndAlign(comTableRowOne.getCell(1),"1500",STVerticalJc.CENTER,STJc.CENTER);
            setCellWitchAndAlign(comTableRowOne.getCell(2),"1500",STVerticalJc.CENTER,STJc.CENTER);
            setCellWitchAndAlign(comTableRowOne.getCell(3),"1500",STVerticalJc.CENTER,STJc.CENTER);
            setCellWitchAndAlign(comTableRowOne.getCell(4),"3400",STVerticalJc.CENTER,STJc.CENTER);
            XWPFTableRow comTableRow = null;
            // 生成表格内容
            // 根据上面的表格标题 确定列数，所以下面创建的是行数。
            // comTableRow.getCell(1).setText(user.getName()); 确定第几列 然后创建赋值
            // 注意：我这边是列数较少固定的，如果列数不固定可循环创建上面的列数
            for (int i=0;i < list.size();i++) {
                comTableRow = ComTable.createRow();

                // 表格内容的填充
                DisUser user = list.get(i);


                /*-------------------变量替换（get）------------------------*/
                comTableRow.getCell(0).setText(((Integer)(i+1)).toString());
                comTableRow.getCell(1).setText(user.getName());
                comTableRow.getCell(2).setText(user.getSpr());
                comTableRow.getCell(3).setText(user.getTime());
                comTableRow.getCell(4).setText(user.getSspy());
                /*-------------------变量替换（get）------------------------*/


                // 表格内容剧中+单元格大小设置
                setCellWitchAndAlign(comTableRow.getCell(0),"700",STVerticalJc.CENTER,STJc.CENTER);
                setCellWitchAndAlign(comTableRow.getCell(1),"1500",STVerticalJc.CENTER,STJc.CENTER);
                setCellWitchAndAlign(comTableRow.getCell(2),"1500",STVerticalJc.CENTER,STJc.CENTER);
                setCellWitchAndAlign(comTableRow.getCell(3),"1500",STVerticalJc.CENTER,STJc.CENTER);
                setCellWitchAndAlign(comTableRow.getCell(4),"3400",STVerticalJc.CENTER,STJc.CENTER);
            }


            //输出word内容文件流，文件形式
            FileOutputStream fos = new FileOutputStream(outFilePath);
            document.write(fos);
            fos.flush();
            fos.close();

        } catch (Exception e1) {
            e1.printStackTrace();
        }finally{

        }
    }


    // 给生成的表格设置样式
    private static void setCellWitchAndAlign(XWPFTableCell cell, String width, STVerticalJc.Enum typeEnum, STJc.Enum align){
        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        ctPr.addNewVAlign().setVal(typeEnum);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(align);
        CTTblWidth ctTblWidth = (ctPr != null && ctPr.isSetTcW() && ctPr.getTcW()!=null &&ctPr.getTcW().getW()!=null) ? ctPr.getTcW(): ctPr.addNewTcW();
        if(StringUtils.isNotBlank(width)){
            ctTblWidth.setW(new BigInteger(width));
            ctTblWidth.setType(STTblWidth.DXA);

        }
    }

}
